package com.the9tcat.deliverycoming;

//import com.adview.AdViewLayout;
import com.feedback.NotificationType;
import com.feedback.UMFeedbackService;
import com.mobclick.android.MobclickAgent;
import com.the9tcat.deliverycoming.component.DeliveryAdapter;
import com.the9tcat.deliverycoming.component.DeliveryBroadcast;
import com.the9tcat.deliverycoming.data.Configure;
import com.the9tcat.deliverycoming.db.DeliveryDb;
import com.the9tcat.deliverycoming.db.DeliveryDbAdapter;
import com.the9tcat.deliverycoming.modle.DeliveryInfo;
import com.the9tcat.deliverycoming.net.HttpClient;
import com.waps.AdView;
import com.waps.AppConnect;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @author       Aliusa 
 * @class        DeliveryComing 
 * @description  
 * @notes        
 * @copyright    Aug 8, 2011 12:51:24 PM. All rights reserved.
 */
public class DeliveryComingActivity extends Activity {
    
    private ListView deliveryList;
    private DeliveryAdapter deliveryAdapter;
    private Cursor cursor;
    private BroadcastReceiver deliveryReceiver;
    private boolean isInUpdate = false;
    public static boolean app_running = false;
    private TextView noexpress;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	app_running = true;
    	//umeng's auto-update check
    	MobclickAgent.update(this);
        super.onCreate(savedInstanceState);
        //db = new DeliveryDb(this);
        if(Configure.getInstance(this).getAdPositionIndex()==0){
        	setContentView(R.layout.deliverycoming_main);
        }else{
        	setContentView(R.layout.deliverycoming_main_bottom);
        }
        
        AppConnect.getInstance(this);
        
        LinearLayout container =(LinearLayout)findViewById(R.id.AdLinearLayout);
        new AdView(this,container).DisplayAd(20);
        
        noexpress = (TextView)findViewById(R.id.noexpress);
        setEventOnButtonAdd();
        setListView();
        showNoExpress();
        //ads
//        initAd();
        UMFeedbackService.enableNewReplyNotification(this, NotificationType.AlertDialog);
    }

    
    @Override
	protected void onDestroy() {
    	AppConnect.getInstance(this).finalize();
    	app_running = false;
    	DeliveryDb.getDb(this).close();
    	unRegisterDeliveryUpdateReveiver();
		super.onDestroy();
	}


	/**
     * *********************************************************
     * @function    setListView      
     * @description 
     * @notes
     * @author      Aliusa      
     * @copyright   Aug 8, 2011 12:51:28 PM. All rights reserved.
     * 
     * **********************modify history*********************
     * 2011/09/18 remove the code of closing db.
     ***********************************************************
     */
    private void setListView(){
        //bind listview 
        deliveryList = (ListView)this.findViewById(R.id.ListView_delivery);
        deliveryList.setFastScrollEnabled(true);
        deliveryList.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo info) {
				
				final int _id = cursor.getInt(cursor.getColumnIndexOrThrow(DeliveryDbAdapter.KEY_ROWID));
				final DeliveryDb db = DeliveryDb.getDb(getApplicationContext());
				final DeliveryInfo delivery = db.getDelivery(_id);
				
				MenuItem sign = menu.add(R.string.delivery_menu_sign);
				if (delivery.isSigned()) {
					sign.setTitle(R.string.delivery_menu_unsign);
				}
				sign.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem arg0) {
						if (delivery.isSigned()) {
							db.updateSigned(_id, 0);
						} else {
							db.updateSigned(_id, 1);
						}
						return false;
					}
				});
				
            	if (!delivery.isSigned()) {
            	    final MenuItem update = menu.add(R.string.delivery_menu_update);
                    update.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem arg0) {
                            if (isInUpdate) {
                                return false;
                            }
                            update.setEnabled(false);
                            new AsyncTask<Void, Void, Boolean>() {
                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    isInUpdate = true;
                                    HttpClient.newInstance().updateDeliveryDetails(delivery, null);
                                    boolean b = db.update(delivery);
                                    return b;
                                }

                                @Override
                                protected void onPostExecute(Boolean result) {
                                    if (result) {
                                        refreshListView();
                                    }
                                    isInUpdate = false;
                                    update.setEnabled(true);
                                }
                            }.execute(new Void[]{});
                            return false;
                        }
                    });
            	}
            	MenuItem delete = menu.add(R.string.delivery_menu_delete);
            	delete.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem arg0) {
						AlertDialog.Builder builder = new AlertDialog.Builder(DeliveryComingActivity.this);
		                builder.setTitle(R.string.dialog_delete_title).setMessage(R.string.dialog_delete_info);
		                builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which) {
		                        DeliveryDb db = DeliveryDb.getDb(getApplicationContext());
                               // db.open();
		                        db.delete(_id);
		                       // db.close();
		                    }
		                });
		                builder.setNegativeButton(R.string.button_cancel, null);
		                builder.create().show();
		                return false;
					}
				});
			}
		});
        DeliveryDb db = DeliveryDb.getDb(getApplicationContext());
//        try{
            cursor = db.getTrackCursor();
            //final Uri uri = Uri.parse("content://com.the9tcat.deliverycoming/tracklist");
            //cursor.setNotificationUri(getContentResolver(), uri);
//            if (cursor.moveToFirst()){
                deliveryAdapter = new DeliveryAdapter(this, cursor);
                deliveryList.setAdapter(deliveryAdapter);
                deliveryList.setOnItemClickListener(new OnItemClickListener() {
    
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        cursor.moveToPosition(position);
                        final int _id = cursor.getInt(cursor.getColumnIndexOrThrow(DeliveryDbAdapter.KEY_ROWID));
                        gotoDetailPage(_id);
                    }
                });
//            }else{
//                deliveryList.setBackgroundResource(R.drawable.about_logo);
//            }
//        } finally{
//            db.close();
//        }
        
    }
    
    /**
     * *********************************************************
     * @function    gotoDetailPage
     * @param _id
     * @description 
     * @notes
     * @author      Aliusa      
     * @copyright   Aug 8, 2011 2:30:41 PM. All rights reserved.
     ***********************************************************
     */
    private void gotoDetailPage(int _id){
        Intent intent = new Intent();
        intent.setClass(DeliveryComingActivity.this, DeliveryDetailActivity.class);
        intent.putExtra("trackId", _id);
        startActivity(intent);
    }
    
    /**
     * *********************************************************
     * @function    setEventOnButtonAdd      
     * @description 
     * @notes
     * @author      Aliusa      
     * @copyright   2011-8-12 上午12:49:59. All rights reserved.
     ***********************************************************
     */
    private void setEventOnButtonAdd() {
        OnClickListener addListener = new ImageView.OnClickListener(){
             @Override
             public void onClick(View v) {
                 Intent intent = new Intent();
                 intent.setClass(DeliveryComingActivity.this, DeliveryAddActivity.class);
                 startActivity(intent);
             }
        };
        findViewById(R.id.add_item).setOnClickListener(addListener);
        
        
    }
    
    /**
     * *********************************************************
     * @function    registerDeliveryUpdateReveiver      
     * @description 
     * @notes
     * @author      Aliusa      
     * @copyright   Aug 15, 2011 3:15:51 PM. All rights reserved.
     ***********************************************************
     */
    private void registerDeliveryUpdateReveiver(){
        deliveryReceiver = new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context context, Intent intent) {
                refreshListView();
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(DeliveryBroadcast.ACTION);
        registerReceiver(deliveryReceiver, filter);
    }
    
    private void unRegisterDeliveryUpdateReveiver(){
    	this.unregisterReceiver(deliveryReceiver);
    }
    
    /**
     * *********************************************************
     * @function    refreshListView      
     * @description 
     * @notes
     * @author      Aliusa      
     * @copyright   Aug 15, 2011 3:20:13 PM. All rights reserved.
     * 
     * 
     * **********************modify history*********************
     * 2011/09/18 remove the code of closing db.
     ***********************************************************
     */
    private void refreshListView(){
        DeliveryDb db = DeliveryDb.getDb(getApplicationContext());
//        try{
            //db.open();
            cursor = db.getTrackCursor();
            ((CursorAdapter)deliveryList.getAdapter()).changeCursor(cursor);
            
//        }finally{
//            db.close();
//        }
        
    }
    private void showNoExpress(){
    	if(deliveryList!=null&&deliveryList.getAdapter()!=null){
    		if(deliveryList.getAdapter().isEmpty()){
    			noexpress.setVisibility(View.VISIBLE);
            }else{
            	noexpress.setVisibility(View.GONE);
            }
    	}
    }
//    private void initAd() {
//        LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
//        if (layout == null) 
//            return;
//        /*delete these two line when release*/
////        AdViewTargeting.setUpdateMode(UpdateMode.EVERYTIME); 
////        AdViewTargeting.setRunMode(RunMode.TEST);  
//        //        
//        AdViewLayout adViewLayout = new AdViewLayout(this, "SDK20112322270845e21nvjcswpn3cod");
//        RelativeLayout.LayoutParams adViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
//        layout.addView(adViewLayout, adViewLayoutParams);
//        
//        layout.invalidate();
//       
//    }

    /* (non-Javadoc)
     * @see android.app.Activity#onCreateOptio
     * nsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        
        return true;
    }
    
	/* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        
        switch(item.getItemId()){
        case R.id.menu_setting:
            Intent intent = new Intent(this,SettingActivity.class);
            this.startActivity(intent);
            return true;
            
        case R.id.menu_add:
            Intent intentAdd = new Intent();
            intentAdd.setClass(DeliveryComingActivity.this, DeliveryAddActivity.class);
            startActivity(intentAdd);
            return true;
            
        case R.id.menu_updateAll:
          Intent updateAll = new Intent();
          updateAll.setClass(this, MessengerService.class);
          this.startService(updateAll);
          return true;
          
        default:
            return super.onOptionsItemSelected(item);
        }
        
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        registerDeliveryUpdateReveiver();
    }
    
	@Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        showNoExpress();
    }


	@Override
    protected void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
    }
	
}